package com.learning.job.schedule.quartz.cluster.jdbc;


import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * ClassName: SimpleJobRunner
 * Description:
 * Date: 2018/12/18 10:56 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CronJobRunner {
    public void main(String[] args) throws SchedulerException, IOException {

        // 定义Job
        JobKey jobKey = JobKey.jobKey("CronJob", "CronJob_Group");
        JobDetail jobDetail = JobBuilder.newJob(CronJob.class).withIdentity(jobKey).build();

        // 定义调度规则，使用 CronScheduleBuilder
        TriggerKey triggerKey = TriggerKey.triggerKey("CronTrigger", "CronTrigger_group");
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("*/10 * * * * * ?");

        // // Misfire 机制，默认是 CronTrigger.MISFIRE_INSTRUCTION_SMART_POLICY;
        cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();

        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey)
                .startNow()
                .withSchedule(cronScheduleBuilder)
                .build();

        // 定义调度器
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        ((StdSchedulerFactory) schedulerFactory).initialize(quartzProperties());// 初始化参数

        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.scheduleJob(jobDetail, cronTrigger);
    }

    public Properties quartzProperties() throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("quartz.properties"));
        return properties;
    }
}
